#include "LogStream.h"
#include"TTime.h"
#include<string.h>
#include<unistd.h>
#include<sys/syscall.h>

static thread_local pid_t thread_id = 0;
tmms::base::Logger* tmms::base::g_loger = nullptr;
const char* log_string[] = {
    " TRACE ",
    " DEBUG ",
    " INFO ",
    " WRING ",
    " ERRPR "
};

tmms::base::LogStream::LogStream(Logger *log, const char *file, int line, LogLevel level, const char *func)
:logger_(log)
{
    const char* file_name = strrchr(file,'/');
    if(file_name){
        file_name = file_name + 1; 
    }else{
        file_name = file;
    }

    stream_ << TTime::ISOTime()<<" ";
    if(thread_id == 0){
        thread_id = static_cast<pid_t>(::syscall(SYS_gettid));
    }
    stream_<< thread_id;
    stream_<< log_string[level];
    stream_<< "[" << file_name << ":" << line <<"]";
    if(func){
        stream_<<"["<<func<<"]";
    }   
}

tmms::base::LogStream::~LogStream()
{
    stream_<<"\n";
    logger_->Write(stream_.str());
}